package com.service.impl;

import com.dao.ChapterDao;
import com.dto.ChapterWithLessonsDTO;
import com.entity.ChapterEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.utils.PageUtils;
import com.utils.Query;


import com.dao.LessonDao;
import com.entity.LessonEntity;
import com.service.LessonService;
import com.entity.vo.LessonVO;
import com.entity.view.LessonView;
import java.util.Comparator;

@Service("lessonService")
public class LessonServiceImpl extends ServiceImpl<LessonDao, LessonEntity> implements LessonService {

    @Autowired
    private ChapterDao chapterDao;

    @Autowired
    private LessonDao lessonDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // MP 2.x 的分页查询
        Page<LessonEntity> page = new Page<>(
                Integer.parseInt(params.get("page").toString()),
                Integer.parseInt(params.get("limit").toString())
        );

        page = this.selectPage(
                page,
                new EntityWrapper<LessonEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ChapterWithLessonsDTO> getCourseStructureByCourseId(Long courseId) {
        List<ChapterEntity> chapters = chapterDao.selectList(
                new EntityWrapper<ChapterEntity>()
                        .eq("course_id", courseId)
                        .orderBy("chapter_order", true) // 按章节顺序升序
        );

        if (chapters == null || chapters.isEmpty()) {
            return new ArrayList<>(); // 如果没有章节，返回空列表
        }


        List<LessonEntity> lessons = this.selectList(
                new EntityWrapper<LessonEntity>()
                        .eq("course_id", courseId)
                        .orderBy("chapter_id", true)   // 先按章节ID排序
                        .orderBy("lesson_order", true) // 再按课时顺序排序
        );
        Map<Long, List<LessonEntity>> lessonsByChapterOrder = lessons.stream()
                .collect(Collectors.groupingBy(LessonEntity::getChapterId));


        List<ChapterWithLessonsDTO> chapterWithLessonsList = chapters.stream().map(chapter -> {
            ChapterWithLessonsDTO dto = new ChapterWithLessonsDTO();


            dto.setId(chapter.getId());
            dto.setCourseId(chapter.getCourseId());
            dto.setTitle(chapter.getTitle());
            dto.setChapterOrder(chapter.getChapterOrder());


            // 设置当前章节下的课时列表
            Long chapterId= chapter.getId();
            List<LessonEntity> chapterLessons = lessonsByChapterOrder.getOrDefault(chapterId, new ArrayList<>());

            chapterLessons.sort(Comparator.comparing(LessonEntity::getLessonOrder));
            dto.setLessons(chapterLessons);

            return dto;
        }).collect(Collectors.toList());
        return chapterWithLessonsList;
    }

    @Override
    public List<LessonVO> selectListVO(Wrapper<LessonEntity> wrapper) {
        return baseMapper.selectListVO(wrapper);
    }

    @Override
    public LessonVO selectVO(Wrapper<LessonEntity> wrapper) {
        return baseMapper.selectVO(wrapper);
    }

    @Override
    public List<LessonView> selectListView(Wrapper<LessonEntity> wrapper) {
        return baseMapper.selectListView(wrapper);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Wrapper<LessonEntity> wrapper) {
        Page<LessonView> page = new Query<LessonView>(params).getPage();
        page.setRecords(baseMapper.selectListView(page, wrapper));
        PageUtils pageUtil = new PageUtils(page);
        return pageUtil;
    }

    @Override
    public LessonView selectView(Wrapper<LessonEntity> wrapper) {
        return baseMapper.selectView(wrapper);
    }

    @Override
    public Integer getMaxLessonOrderByChapter(Long chapterId) {
        List<LessonEntity> lessons = this.baseMapper.selectList(
                new EntityWrapper<LessonEntity>()
                        .eq("chapter_id", chapterId)
                        .orderBy("lesson_order", false)
                        .last("LIMIT 1") // 只取最大的一条
        );

        if (lessons != null && !lessons.isEmpty()) {
            return lessons.get(0).getLessonOrder();
        }
        return 0;
    }

    @Override
    public String getCombinedContentForAiByChapterId(Long chapterId) {
        // 调用修改后的 DAO 方法，现在它返回 LessonEntity 列表
        List<LessonEntity> lessons = lessonDao.selectTitleAndContentForAiByChapterId(chapterId);

        if (lessons == null || lessons.isEmpty()) {
            return null;
        }

        // 拼接逻辑：将 title 和 content_for_ai 组合
        return lessons.stream()
                .filter(lesson -> lesson.getContentForAi() != null && !lesson.getContentForAi().trim().isEmpty()) // 过滤掉 content_for_ai 为空或 null 的 lesson
                .map(lesson -> {
                    String title = lesson.getTitle();
                    String content = lesson.getContentForAi();
                    // 格式化输出：例如 "## 课时标题\n课时内容"
                    // 你可以根据需要调整这个格式，例如用 Markdown 标题、或者简单的 "课时标题: 课时内容"
                    return (title != null && !title.trim().isEmpty() ? "## " + title + "\n" : "") + content;
                })
                .collect(Collectors.joining("\n\n---\n\n")); // 每段课时内容之间用分割线和双换行符隔开
    }
}
